import { timeStamp } from 'console'
import { formatWithOptions } from 'util'
import Food from './Food'
import Panel from './Panel'
import Snake from './Snake'


class GameControl {
  food: Food
  snake: Snake
  panel: Panel
  direction: string = ''
  isAlive: boolean = true
  constructor() {
    this.snake = new Snake()
    this.food = new Food()
    this.panel = new Panel(2)
    this.init()
  }

  init() {
    document.addEventListener('keydown', this.keyDownHandler.bind(this))
    this.move()
  }

  keyDownHandler(event: KeyboardEvent) {
    this.direction = event.key
  }
  move() {
    if (this.isAlive) {
      let X = this.snake.X
      let Y = this.snake.Y
      switch (this.direction) {
        case 'ArrowUp':
        case 'Up':
          Y -= 10
          break;
        case 'ArrowRight':
          X += 10
        case 'Right':
          break;
        case 'ArrowDown':
        case 'Down':
          Y += 10
          break;
        case 'ArrowLeft':
        case 'Left':
          X -= 10
          break;
      }
      this.checkEat(X, Y)


      try {
        this.snake.X = X
        this.snake.Y = Y
      } catch (e) {
        alert(e.message + ' Game Over!')

        this.isAlive = false
      }


      setTimeout(this.move.bind(this), 300 - (this.panel.level * 30))
    }
  }

  checkEat(X: number, Y: number) {
    if (this.food.X === X && this.food.Y === Y) {
      this.panel.addScore()
      this.food.change()
      this.snake.addBody()
    }

  }

}


export default GameControl
